<template>
  <div>
    <p>sort 的实现原理</p>
    <table id="table" width="1000px" border="1">
      <thead>
        <tr>
          <td>章节</td>
          <td>类型</td>
          <td>知识点</td>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</template>

<script>
import tableData from '../utils/tableData'
export default {
  name: 'sort',
  mounted () {
    this.init()
    this.sort()
  },
  methods: {
    init () {

      let tables = document.querySelector('#table')
      let tbody = tables.tBodies[0]

      let datas = tableData.data

      datas.sort((a, b) => {
        return a.chapter - b.chapter
      })

      tbody.innerHTML = this.getTable(datas)
    },
    getTable (items) {

      return items.map( item => {
        return `
          <tr>
            <td>${item.chapter}</td>
            <td>${item.type}</td>
            <td>${item.title}</td>
          </tr>
        `
      } ).join('')
    },

    // sort 原理
    sort () {
      let arr = [6, 1, 2, 7, 9, 3, 4, 10, 8]

      let newArr = []

      for(let j = 0; j < arr.length - 1; j ++) {
        let isOk = true
        for( let i = 0; i < arr.length - 1 - j; i++ ){
          let a = arr[i]
          let b = arr[i + 1]
          if (a > b) {
            arr[i] = b
            arr[i + 1] = a
            isOk = false
          }
        }

        if (isOk) {
          break;
        }
      }
    }
  }
}
</script>

<style>

</style>
